package com.example.backgroundmanger.config;

import com.example.backgroundmanger.interceptor.JwtInterceptor;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${file.upload-dir}")
    private String uploadDir;
    
    @Resource
    private JwtInterceptor jwtInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置静态资源映射
        String avatarPath = "file:" + uploadDir + "/avatar/";
        System.out.println("Avatar physical path: " + avatarPath);
        
        registry.addResourceHandler("/api/avatar/**")
                .addResourceLocations(avatarPath);
        
        registry.addResourceHandler("/avatar/**")
                .addResourceLocations(avatarPath);
        
        System.out.println("Static resource mapping: /avatar/** -> " + avatarPath);
    }
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .maxAge(3600);
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册JWT拦截器，拦截所有路径，但在拦截器内部进行路径过滤
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**");
    }
} 